﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace GameEngine
{
    public class Layer
    {
        //------------------- Vars

        int[,] layer;
        int width, height, tile_width, tile_height;
        float alpha = 1.0f;
        Sprite spritesheet;

        //------------------- Constructs

        public Layer(int width, int height, Sprite spritesheet, int tile_width, int tile_height, float alpha = 1.0f)
        {
            layer = new int[height, width];

            this.spritesheet = spritesheet;

            this.width = width;
            this.height = height;

            this.tile_width = tile_width;
            this.tile_height = tile_height;

            this.alpha = alpha;
        }

        public Layer(int[,] existingMap, Sprite spritesheet, int tile_width, int tile_height, float alpha = 1.0f)
        {
            layer = (int[,])existingMap.Clone();

            this.spritesheet = spritesheet;

            this.width = existingMap.GetLength(1);
            this.height = existingMap.GetLength(0);

            this.tile_width = tile_width;
            this.tile_height = tile_height;

            this.alpha = alpha;
        }

        //------------------- Functions

        public void SetCellIndex(int x, int y, int i)
        {
            layer[y, x] = i;
        }

        //------------------- Base functions

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullCounterClockwise);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (layer[y, x] == -1)
                        continue;

                    spriteBatch.Draw(
                        spritesheet.Texture,
                        new Vector2(tile_width * x, tile_height * y),
                        spritesheet.GetRegion(layer[y,x]),
                        new Color(new Vector4(1, 1, 1, alpha)));
                }
            }

            spriteBatch.End();
        }
    }
}
